package com.bindapp.http;

import com.bindapp.listener.HttpListener;
import com.bindapp.util.Static;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by apple on 2018/6/29.
 */

public class QueueRequest {

    public static QueueRequest queueRequest;
    public BlockingQueue<Object[]> blockingQueue;//Map<String,Object>
    public Thread takeTh;
    public boolean isActive=false;

    public static QueueRequest getInstance(){
        if(queueRequest==null){
            queueRequest=new QueueRequest();
            queueRequest.blockingQueue=new ArrayBlockingQueue<Object[]>(3);
        }
        return queueRequest;

    }

    //clazz key
    public void addListRequest(Map<String,Object> map,Class<?> clazz,HttpListener listener){
        try {
            Object[] objs=new Object[]{map,clazz,listener};
            blockingQueue.put(objs);
            if(!isActive){
                startTh();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void startTh(){
        if(blockingQueue.size()>0){
            isActive=true;
            Thread t=new Thread(){
                @Override
                public void run() {
                    try {
                        Object[] takeItem=blockingQueue.take();
                        Map<String,Object> params = (Map<String,Object>)takeItem[0];
                        Class<?> clazz = (Class<?>)takeItem[1];
                        final HttpListener listener=(HttpListener)takeItem[2];
                        MNetSocketHttp.getInstance().getNormalRequest(params, clazz, new HttpListener() {
                            @Override
                            public void success(Object obj) {
                                Static.myLog("success");
                                listener.success(obj);
                                startTh();
                            }

                            @Override
                            public void fail(String msg) {
                                Static.myLog("fail");
                                listener.fail(msg);
                                startTh();
                            }
                        });

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }else{
            isActive=false;
        }


    }




}
